package com.huawei.obs;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.rds.v3.RdsClient;
import com.huaweicloud.sdk.rds.v3.model.DownloadSlowlogRequest;
import com.huaweicloud.sdk.rds.v3.model.DownloadSlowlogResponse;
import com.huaweicloud.sdk.rds.v3.model.SlowlogDownloadRequest;
import com.huaweicloud.sdk.rds.v3.region.RdsRegion;
import com.obs.services.ObsClient;
import com.obs.services.model.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class RDSSlowlogUploadOBS {
    //自定义存储文件名
    static String fileName = "fileName";
    public static void main(String[] args) {
        //你需要提供下面这些参数
        String endPoint,ak,sk,areaCode,instanceID,obsName,dirName;
        //下面是各变量值的获取方式：
        //endPoint获取方式参考：https://developer.huaweicloud.com/endpoint获取对应的endPoint值。注意：endpoint值由很多，要找到OBS下面的endpoint
        endPoint = "endPoint";
        //ak与sk获取方式参考：https://support.huaweicloud.com/iam_faq/iam_01_0618.html
        ak = "ak";
        sk = "sk";
        //区域码获取方式，参考：https://developer.huaweicloud.com/endpoint
        areaCode = "areaCode";
        //instanceID实例ID需要在华为云的RDS实例管理界面中获取实例ID
        instanceID = "instanceID";
        //OBS桶名
        obsName = "obsName";
        //自定义OBS存储路径
        dirName = "logs/slowlogs/"+instanceID+"/";
        //获取下载链接
        List<String> fileLinks = DownloadSlowlog(ak,sk,areaCode,instanceID);
        int i = 0;
        while (fileLinks == null) {
            System.out.println("链接正在创建中，正在进行第"+(i+1)+"次重试！");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            fileLinks = DownloadSlowlog(ak,sk,areaCode,instanceID);
            i++;
            if(i == 30){
                System.out.println("获取链接失败，请手动重试并检查下载资源！");
                break;
            }
        }
        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        InputStream inputStream = null;
        try {
            //用来
            int num = 0;
            for(String fileLink:fileLinks){
                num++;
                //获取链接文件大小
                long filelength = new URL(fileLink).openConnection().getContentLength();
                //根据文件名获取obs上对应文件的大小
                long obsFilelength = filelength(obsClient,obsName, dirName+ fileName + "_" + num,obsName);
                //判断链接文件大小和obs文件大小是否一致
                if (filelength != obsFilelength) {
                    inputStream = new URL(fileLink).openStream();
                    PutObjectRequest request = new PutObjectRequest();
                    //设置OBS桶名
                    request.setBucketName(obsName);
                    //设置在OBS桶中的存储位置,存储位置可以自行设置，如在OBS桶中无对应文件夹，会自动创建。
                    request.setObjectKey(dirName + fileName + "_" + num);
                    request.setInput(inputStream);
                    obsClient.putObject(request);
                    System.out.println("上传成功");
                }else {
                    System.out.println("文件一样，无需更新！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    /**
     * 获取慢日志下载路径
     * @param ak
     * @param sk
     * @param areaCode
     * @param instanceID
     * @return
     */
    public static List<String> DownloadSlowlog(String ak, String sk, String areaCode, String instanceID){
        List<String> fileLinks = new ArrayList();
        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        RdsClient client = RdsClient.newBuilder()
                .withCredential(auth)
                .withRegion(RdsRegion.valueOf(areaCode))
                .build();
        DownloadSlowlogRequest request = new DownloadSlowlogRequest();
        request.withXLanguage(DownloadSlowlogRequest.XLanguageEnum.fromValue("zh-cn"));
        request.withInstanceId(instanceID);
        SlowlogDownloadRequest body = new SlowlogDownloadRequest();
        request.setBody(body);
        try {
            DownloadSlowlogResponse response = client.downloadSlowlog(request);
            if (response.getStatus().equals("CREATING")){
                return null;
            }
            for(int count = 0; count < response.getCount(); count++){
                fileLinks.add(count,String.valueOf(response.getList().get(count).getFileLink()));
            }

        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return fileLinks;
    }

    /**
     * 判断文件是否存在，存在返回  存在返回长度 filelength ，不存在返回长度filelength为 0
     * @param obsClient
     * @param bucketName
     * @param obejctName
     * @return
     */

    public static long filelength(ObsClient obsClient, String bucketName, String obejctName,String obsName) {
        ListObjectsRequest request = new ListObjectsRequest(bucketName);
        request.setDelimiter("/");
        request.setPrefix(obejctName);
        ObjectListing result = obsClient.listObjects(request);
        long filelength = 0;
        for (ObsObject obsObject : result.getObjects()) {
            String objectName = obsObject.getObjectKey();
            if (objectName == null) {
                filelength = 0;
            } else {
                ObjectMetadata metadata = obsClient.getObjectMetadata(obsName, objectName);
                filelength = metadata.getContentLength();
            }
        }
        return  filelength;
    }
}
